import {useEffect, useState, useRef } from 'react';
import {useDispatch} from 'react-redux'
import { InputItem, Button, Toast } from 'antd-mobile';
import { useHistory } from 'react-router-dom'
import {LoginSty} from './style'
import storage from '@/utils/storage'
import {throttle} from 'lodash'

import net from '@/api/net'

const Login = () => {

  const dispatch = useDispatch()
  const [checkoutPanel, setCheckoutPanel] = useState(["active",""]);

  const [validateBtnActive, setValidateBtnActive] = useState("");

  //"jump":验证前 , "rotate":验证中 , "stop":验证完成
  const [validateBtnState, setvalidateBtnState] = useState("jump");
  const [validateTip, setValidateTip] = useState("点击按钮开始智能验证");

  //用户名密码
  const [loginUserName, setLoginUserName] = useState('');
  const [loginPassword, setLoginPassword] = useState('');
  const [registUserName, setregistUserName] = useState('');
  const [registPassword, setregistPassword] = useState('');

  //tip
  const  tip = useRef()

  useEffect(() => {
    dispatch({
      type: 'setFooterMenu',
      data: "none"
    })
    return () => {
      dispatch({
        type: 'setFooterMenu',
        data: "block"
      })
    }
  },[]);

  const history = useHistory();

  const checkFinsh = () => {
    setTimeout(() => {
      setvalidateBtnState("stop")
      setValidateTip("验证成功")
    }, 2000);
  }

  const validateLogin = () => {
    //校验用户名密码
    if(loginUserName === "" || loginPassword === ""){
      tip.current.innerHTML = "用户名或密码不能为空"
      return false
    }
    return true
  }
  const validateRegister = () => {
    //校验用户名密码
    if(registUserName === "" || registPassword === ""){
      tip.current.innerHTML = "用户名或密码不能为空"
      return false
    }
    return true
  }
  const submit = async () => {
    if(checkoutPanel[1]){
      //注册逻辑
      if(!validateRegister()){
        return;
      }
      const data = await net.post('/api/register',{
        username:registUserName,
        password:registPassword
      });
      if(data.code === 1000){
        Toast.info("注册成功，请返回登录", 1);
        tip.current.innerHTML = ''
      }
    }else{
      //登录
      if(!validateLogin()){
        return;
      }
      const data = await net.post('/api/login',{
        username:loginUserName,
        password:loginPassword
      });
      if(data.msg === "ok"){
        history.push('/home')
        storage.set('token' , data)
      }
      else if(loginUserName !=='' && loginPassword !==''){
        Toast.info(data.msg, 1);
        tip.current.innerHTML = data.msg
      }
    }
  } 

  const validateUsername = (value) => {
    throttle( async () => {
      const {code} = await net.post('/api/validate',{
        username: value,
        password: "1"
      })
      if(code === 1001){
        tip.current.innerHTML = "该名字已被人注册"
      }else{
        tip.current.innerHTML = ""
      }
    } , 2000)(value);
  }
  const changePanel = () => {
    setValidateBtnActive("active");
    setvalidateBtnState("rotate");
    checkFinsh();
    setValidateTip("验证中...")
  }
  return (
    <LoginSty>
      <div className="login-block-operate-m">
        <div className="tab">
          <div className={checkoutPanel[0]} onClick={()=>{tip.current.innerHTML = "";setCheckoutPanel(["active",""])}}>密码登录</div>
          <div className={checkoutPanel[1]} onClick={()=>{tip.current.innerHTML = "";setCheckoutPanel(["","active"])}}>注册</div>
        </div>
        <div className={"panel "+checkoutPanel[0]}>
          <InputItem
            onBlur={value => setLoginUserName(value)}
            type="text"
            placeholder='登录名/手机号/邮箱'
            clear
            className="text_input"
            />
          <InputItem
            onBlur={value => setLoginPassword(value)}
            type="password"
            className="text_input"
            placeholder='请输入密码'
            clear
          />
        </div>
        <div className={"panel "+checkoutPanel[1]}>
          <InputItem
            onBlur={value => setregistUserName(value)}
            onChange={value => validateUsername(value)}
            type="text"
            placeholder='请输入用户名'
            clear
            className="text_input"
            />
          <div className="send_validate">
            <InputItem
              onBlur={value => setregistPassword(value)}
              type="password"
              className="text_input"
              placeholder='请输入密码'
              clear
            />
            {/* <Button type="warning">发送验证码</Button> */}
          </div>
        </div>
        <div className="sm-btn" onClick={()=>{changePanel()}}>
          <div className={"sm-ico "+ validateBtnState}>
            <div className="sm-ico-wave"></div>
            <div className="out-silder-circle"></div>
          </div>
          <span className="sm-txt">{validateTip}</span>
          <div className={"border "+ validateBtnActive}>
            <div className="top"></div>
            <div className="bottom"></div>
          </div>
        </div>
        <div className="submit">
          <div ref={tip} className="tip"></div>
          <Button type="warning" onClick={()=>submit()}>{checkoutPanel[0]?"立即登录":"立即注册"}</Button>
          <div className="forgetPassword">
            {/* <span>忘记密码?</span> */}
          </div>
        </div>
      </div>
    </LoginSty>
  );
}

export default Login;
